package com.chuangping.mvp.presenter;

import android.app.Application;
import android.text.TextUtils;

import com.chuangping.mvp.contract.LoginContract;
import com.chuangping.mvp.model.entity.Login;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void login(String name, String pwd) {

        mModel.login(name, pwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<Login>(mErrorHandler) {
                    @Override
                    public void onNext(Login login) {
                        mRootView.killMyself();
                    }

                    @Override
                    public void onError(Throwable t) {
                        mRootView.showMessage("验证码错误");
                    }
                });
    }

    private boolean checkMobile(String mobile) {
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11) {//手机号为空
            mRootView.showMessage("请输入正确的用户名");
            return true;
        }
        return false;
    }

}
